<template>
  <div class="lix-container lix-cod__bg">
    <div class="lix-cod__header">
      <div class="lix-cod__noaddress" v-if="address.list.length === 0 && addressInfo === null" @click="go2AddressPage">
        新增收货地址
        <image src="../static/images/arrow.png"/>
      </div>
      <div class="lix-cod__address" v-else>
        <div class="left">
          <div class="topline">
            <div>{{ addressInfo.name }}</div>
            <div>{{ addressInfo.tel }}</div>
          </div>
          <div class="bottomline">
            <div>{{ addressInfo.address }}</div>
          </div>
        </div>
        <div class="right" @click="go2AddressPage">
          <image src="../static/images/arrow.png"/>
        </div>
      </div>
    </div>
    <div class="lix-cod__form">
      <div class="cell-group">
        <div class="cell-product" v-for="(item, idx) in shoplist" :key="idx">
          <div class="icon">
            <image :src="item.thumb"/>
          </div>
          <div class="right">
            <div class="product-info">
              <div class="title">{{ item.name }}</div>
              <div class="sku">{{ item.sku }}</div>
            </div>
            <div class="price-info">
              <div class="price"><span>￥</span>{{ item.price }}</div>
              <div class="num">x{{ item.num }}</div>
            </div>
          </div>
        </div>
        <div class="cell-freight cell">
          <div>运费</div>
          <div v-if="order.express === 0">包邮</div>
          <div v-else>{{ order.express }}</div>
        </div>
        <div class="cell-price cell">
          <div>小计</div>
          <div><span>￥</span>{{ order.subtotal }}</div>
        </div>
      </div>
    </div>
    <div class="lix-cod__footer">
      <div class="left">共{{ shopcount }}件，应付金额<div class="price"><span>￥</span>{{ order.subtotal }}</div> </div>
      <div class="right"><button @click="submit">去付款</button></div>
    </div>
  </div>
</template>

<script>
import { packShopApi, createOrderApi, createTradeOrderApi } from '../api';
import Tip from '../utils/tips.js';

export default {
  data: {
    noaddress: false,
    chosenAddressId: 0,
    addressInfo: null,
    address: {
      list: []
    },
    shoplist: [],
    order: {
      amount: 0.00,
      discount: 0,
      express: 0,
      subtotal: 0.00
    },
    shopcount: 0,
    orderId: 0
  },
  onLoad() {
    this.getShopData();
  },
  onShow() {
    const item = wx.getStorageSync('SELECTED_ADDRESS');
    if (item) {
      console.log(item);
      const addressInfo = item;
      addressInfo.address = item.province + item.city + item.country + ' ' + item.addressDetail;
      this.addressInfo = addressInfo;
      this.chosenAddressId = addressInfo.id;
      wx.setStorageSync('SELECTED_ADDRESS', null);
    } else {
      console.log('没有找到地址信息');
    }
  },
  methods: {
    getShopData() {
      packShopApi()
        .then(res => {
          console.log(res);
          const data = res.data;
          this.address = data.address;
          this.shoplist = data.list;
          this.order = data.order;

          let sum = 0;
          for (let i = 0; i < data.list.length; i++) {
            sum += data.list[i].num;
          }
          this.shopcount = sum;

          // 保存地址信息
          const chosenAddressId = data.chosenAddressId;
          if (chosenAddressId) {
            this.chosenAddressId = chosenAddressId;
            data.address.list.forEach((curr) => {
              if (curr.id === chosenAddressId) {
                console.log('找到对应的地址 ', curr);
                this.addressInfo = curr;
              }
            });
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    go2AddressPage(e) {
      wx.navigateTo({
        url: '/pages/address?type=Chose'
      });
    },
    getCartIds() {
      let result = [];
      for (let i = 0; i < this.shoplist.length; i++) {
        result[i] = this.shoplist[i]['id'];
      }
      return result;
    },
    submit(e) {
      console.log('选择地址id: ', this.chosenAddressId);
      if (this.orderId === 0) {
        createOrderApi({
          address_id: this.chosenAddressId,
          carts: this.getCartIds(),
          coupons: []
        })
          .then(res => {
            console.log(res);
            this.orderId = res.data.id;
            this.tradeOrderCreate();
          })
          .catch(e => {
            console.log(e);
          });
      } else {
        this.tradeOrderCreate();
      }
    },
    tradeOrderCreate() {
      createTradeOrderApi({
        'order_id': this.orderId,
        'scope': 'shop',
        'paymode': 'wechat'
      })
        .then(res => {
          console.log(res);
          Tip.confirm(`请确认支付${this.order.subtotal}元的订单`)
            .then(() => {
              console.log('确认');
              this.createWechatPay(res.data.wechat);
            })
            .catch(() => {
              console.log('取消');
            });
        })
        .catch(e => {
          console.log(e);
        });
    },
    createWechatPay(data) {
      const self = this;
      console.log('调起微信支付');
      console.log(data);
      wx.requestPayment({
        'timeStamp': data.timeStamp,
        'nonceStr': data.nonceStr,
        'package': data.package,
        'signType': data.signType,
        'paySign': data.paySign,
        'success': function(res) {
          console.log(res);
          Tip.success('支付成功');
        },
        'fail': function(res) {
          console.log('fail');
          console.log(res);
          // Tip.error(res.err_desc);
          Tip.error('支付失败');
          wx.redirectTo({
            url: '/pages/order?id=' + self.orderId
          });
        },
        'complete': function(res) {
          console.log('complete');
          console.log(res);
        }
      });
    }
  }
};
</script>

<style lang="scss">
@import "../theme-chalk/createOrder.scss";
</style>
